/**
 * Created by Administrator on 2017/10/13.
 */
import cookie from "js-cookie";
import { Toast } from 'antd-mobile';
import { routerRedux } from 'dva/router';
import { login, edit } from '../services/login';

const _ = require('lodash');

export default {

  namespace: 'login',

  state: {

  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // if(pathname == '/') {
        //   dispatch({
        //     type:'fetch',
        //   })
        // }
      });
    }
  },

  effects: {
    *fetch({ payload }, { call, put, select }) {
      // sessionStorage.removeItem("userdata");
      const payloadd = {
        username: payload.username,
        password: payload.password,
      };
      const data = yield call(login, payloadd);
      if (!_.isEmpty(data)) {
        yield put({
          type: 'success',
          payload: {
            data
          }
        });
        // 用户 model 初始化
        yield put({
          type: 'user/initialization',
          payload: data.data.ret,
        });

        const datambers = [
          {
            administrator: [
              { id: data.data.ret.administrator.id },
              { username: data.data.ret.administrator.username },
              { realname: data.data.ret.administrator.realname },
              { avatar: data.data.ret.administrator.avatar },
              { member_code: data.data.ret.administrator.member_code },
            ]
          },
          {
            orgs: [
              [
                { org_code: data.data.ret.orgs["050026075658"].org_code },
                { org_zb_code: data.data.ret.orgs["050026075658"].org_zb_code },
                { org_name: data.data.ret.orgs["050026075658"].org.name }
              ],
              [
                { org_code: data.data.ret.orgs["050026119417"].org_code },
                { org_zb_code: data.data.ret.orgs["050026119417"].org_zb_code },
                { org_name: data.data.ret.orgs["050026119417"].org.name }
              ]
            ]
          },
        ];

        // 用户信息存入session
        const userjosn = JSON.stringify(datambers);
        sessionStorage.setItem("userdata", userjosn);
        yield put(
          routerRedux.push('/home')
        );
      } else {
        yield put(
          routerRedux.push('/login'),
        );
      }
    },
    //修改密码
    *edit({payload}, { call, put, select }) {
      const data =yield call(edit,payload);
      if (data.data.code == 200) {
        Toast.success('修改成功！', 1);
        yield put({
          type: 'success',
          payload: {
             data
          }
        });
      } else {
        Toast.success('修改失败！', 1);
      }
    },
  },

  reducers: {
    success(state, action) {
      return { ...state, ...action.payload };
    },
  }
};
